package com.cheng.rebuildproject.server.impl;

import com.cheng.rebuildproject.constant.RedisConstant;
import com.cheng.rebuildproject.mapper.UserMapper;
import com.cheng.rebuildproject.pojo.LoginUser;
import com.cheng.rebuildproject.pojo.ResponseResult;
import com.cheng.rebuildproject.pojo.User;
import com.cheng.rebuildproject.server.UserServer;
import com.cheng.rebuildproject.util.JwtUtil;
import com.cheng.rebuildproject.util.PasswordEncode;
import com.cheng.rebuildproject.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServerImpl implements UserServer {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AuthenticationManager authenticationManager;
    @Override
    public ResponseResult saveUser(User user) {
        String encode = PasswordEncode.encodePassword(user.getPassword());
        user.setPassword(encode);

        int insert = userMapper.insert(user);

        if(insert > 0){
            return new ResponseResult(200, "用户注册成功");
        }
        return new ResponseResult(-101, "用户注册失败");
    }

    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //如果认证没通过，给出对于提升
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }
        //得到用户id
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Long userId = loginUser.getUser().getId();
        //生成一个jwt，设置过期时间

        String redisKey = RedisConstant.REDIS_KEY_LOGIN_PRE + userId;

        String jwt = JwtUtil.createJWT(String.valueOf(userId));

        Map<String, String> map = new HashMap<>();
        map.put("token",jwt);
        //把完整的用户信息存入redis
        redisTemplate.opsForValue().set(redisKey, loginUser);
        return new ResponseResult(200, "登录成功",map);
    }

    @Override
    public List<String> getUserRoleById(String id) {
        List<String> userRoleById = userMapper.getUserRoleById(id);
        return userRoleById;
    }
}
